import Axios from 'axios';
Axios.defaults.withCredentials = true;
class httpRequest {
    constructor() {
        this.options = {
            method: '',
            url: ''
        };
        this.queue = {};
    }

    destroy(url) {
        delete this.queue[url];
        const queue = Object.keys(this.queue);
        return queue.length;
    }

    interceptors(instance, url) {
        instance.interceptors.request.use(config => {
            return config;
        }, error => {
            return Promise.reject(error);
        });

        instance.interceptors.response.use((res) => {
            const {
                data,
                status
            } = res;
            const is = this.destroy(url);
            if (!is) {
                window.setTimeout(() => {
                }, 500)
            }
            if (status === 200) {
            }
            return res;
        }, (error) => {
            return Promise.reject(error);
        })
    }

    // 创建实例
    create(options) {
        let transformRequest = [];
        if (options.type && options.type === 'formData') {
            transformRequest = [];
        } else {
            transformRequest = [
                function (data) {
                    let ret = "";
                    for (let it in data) {
                        ret += encodeURIComponent(it) + "=" + encodeURIComponent(data[it]) + "&";
                    }
                    return ret;
                }
            ];
        }
        const conf = {
            baseURL: options.baseURL,
            transformRequest: transformRequest
        };
        return Axios.create(conf);
    }

    request(options) {
        let instance = this.create(options);
        if (options.method === 'get') {
            if (!options.params) {
                Object.assign(options, {
                    params: {
                        timestamp: new Date().getTime()
                    }
                });
            } else {
                Object.assign(options.params, {
                    timestamp: new Date().getTime()
                });
            }
        }
        this.interceptors(instance, options.url);
        options = Object.assign({}, options);
        this.queue[options.url] = instance;
        return instance(options);
    }
}
export default httpRequest;
